// pages/apply/index.js
const db = wx.cloud.database();
const app = getApp().globalData;
let Moment = require("./moment.js");
var dateTimePicker = require('./dateTimer.js');
let DATE_LIST = [];
let DATE_YEAR = new Date().getFullYear();
let DATE_MONTH = new Date().getMonth() + 1;
let DATE_DAY = new Date().getDate();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        id: -1,
        type: '',
        eq_data: '',
        user_data: '',
        field_data: '',
        director_data: '',
        showView: true,
        btn_select: true,
        show_date: true,
        date_used: '',
        start_date: '',
        stop_date: '',

      
        end_time: '',
        start_time: '',
        dateTimeArray: '', //时间数组
        startYear: 2022, //最小年份
        endYear: 2050, // 最大年份
        start_time_p: '', //显示的开始时间
        start_time_p: '', //显示的结束时间


        maxMonth: 2, //最多渲染月数
        dateList: [],
        weekStr: ['日', '一', '二', '三', '四', '五', '六'],
        checkInDate: Moment(new Date()).format('YYYY-MM-DD'),
        checkOutDate: Moment(new Date()).add(1, 'day').format('YYYY-MM-DD'),
        markcheckInDate: false, //标记开始时间是否已经选择
        markcheckOutDate: false,   //标记结束时间是否已经选择
        inday: '',
        outday: '',
        sFtv: [
          {
            month:1,
            day:1,
            name:"元旦"
          },
          {
            month: 2,
            day: 14,
            name: "情人节"
          },
          {
            month: 3,
            day: 8,
            name: "妇女节"
          },
          {
            month: 3,
            day: 12,
            name: "植树节"
          },
          {
            month: 3,
            day: 15,
            name: "消费者权益日"
          },
          {
            month: 4,
            day: 1,
            name: "愚人节"
          },
          {
            month: 5,
            day: 1,
            name: "劳动节"
          },
          {
            month: 5,
            day: 4,
            name: "青年节"
          },
          {
            month: 5,
            day: 12,
            name: "护士节"
          },
          {
            month: 6,
            day: 1,
            name: "儿童节"
          },
          {
            month: 7,
            day: 1,
            name: "建党节"
          },
          {
            month: 8,
            day: 1,
            name: "建军节"
          },
          {
            month: 9,
            day: 10,
            name: "教师节"
          },
          {
            month: 9,
            day: 28,
            name: "孔子诞辰"
          },
          {
            month: 10,
            day: 1,
            name: "国庆节"
          },
          {
            month: 10,
            day: 6,
            name: "老人节"
          },
          {
            month: 10,
            day: 24,
            name: "联合国日"
          },
          {
            month: 12,
            day: 24,
            name: "平安夜"
          },
          {
            month: 12,
            day: 25,
            name: "圣诞节"
          }
        ]

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.setData({
            id: getApp().globalData.ID,
            type: getApp().globalData.type
        })
        getApp().globalData.ID = -1
        getApp().globalData.type = -1


        // 获取完整的年月日 时分秒，以及默认显示的数组
        var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
        console.log(obj)
        this.setData({
          start_time: obj.dateTime,
          end_time: obj.dateTime,
          dateTimeArray: obj.dateTimeArray,
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        this.getUser()
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow(options) {
        if(this.data.type == 'field'){
            this.setData({
                'showView': true,
                'btn_select': true
            })
            this.getField()
        }else if(this.data.type == 'eq'){
            this.setData({
                'showView': false,
                'btn_select': false
            })
            this.getEquipment()
        }

        // 页面初始化 options为页面跳转所带来的参数
        this.createDateListData();

        let _this = this;
        // 页面初始化 options为页面跳转所带来的参数
    
        let checkInDate = options.checkInDate ? options.checkInDate : Moment(new Date()).format('YYYY-MM-DD');
        let checkOutDate = options.checkOutDate ? options.checkOutDate : Moment(new Date()).add(1, 'day').format('YYYY-MM-DD');
        _this.setData({ checkInDate, checkOutDate });


        this.setData({
            start_date: getApp().globalData.start,
            stop_date: getApp().globalData.stop
        })


    },
    getField() {
        const db = wx.cloud.database();
        const _ = db.command;
        db.collection('fields').where({
            _id: _.eq(this.data.id)
        }).
        get().then(res => {
            this.setData({
                'field_data': res.data[0],
                'date_used': res.data[0].date_used
            })
            this.getDirector(this.data.field_data.director)
        })
    },
    getEquipment() {
        const db = wx.cloud.database();
        const _ = db.command;
        db.collection('equipments').where({
            _id: _.eq(this.data.id)
        }).
        get().then(res => {
            this.setData({
                'eq_data': res.data[0],
                'date_used': res.data[0].date_used
            })
            this.getDirector(this.data.eq_data.director)
        })
    },
    // 获取审批人相关数据
    getDirector(director){
        const db = wx.cloud.database();
        const _ = db.command;
        db.collection('user').where({
            name: _.eq(director) 
        }).get().then(res => {
            this.setData({
                director_data: res.data[0]
            })
        })
    },
    getUser() {
        const db = wx.cloud.database()
        let openid = getApp().globalData.openid;
        db.collection('user').get(openid=openid).then(res =>{
            this.setData({
                'user_data': res.data[0]
            })
        })
    },
     // 将申请表相关数据汇总起来, 提交给数据库进行存储
     formSubmit_1(e) {

        if(this.data.result_this.message != '当前选择的时间区域可用')return;
        let value = e.detail.value;
        const db = wx.cloud.database();
        const _ = db.command;
        let apply_data = {
            // 申请人
            applicant: this.data.user_data.name,
            // 审批人
            director: this.data.director_data._id,
            // 抄送
            cc: e.detail.value.cc,
            // 审批名称
            director_name: this.data.director_data.name,
            // 场地名称
            field_name: this.data.field_data.name,
            field_id: this.data.field_data._id,
            eq_name: '',
            eq_id: '',
            // 开始时间
            start_date: this.data.start_time_p,
            // 结束时间
            stop_date: this.data.end_time_p,
            // 申请单中的全部数据
            remarks: value,
            // 申请时间
            create_time: new Date().getTime(),

            project: e.detail.value.project,
            reason: e.detail.value.reason,
            pipei: e.detail.value.pipei,
            tpm: e.detail.value.tpm,
            // 默认状态 0,1,2
            state: 0
        }
        let new_data_used = getApp().globalData.new_date_used;
        if(new_data_used != -1 || new_data_used != undefined){
            // 修改data_used
            db.collection('fields').doc(this.data.id).update({
                data:{
                    date_used: _.set(new_data_used)
                }
            })
        }
        db.collection('applys').add({
            data: apply_data,
            success: res => {
                db.collection("fields").doc(this.data.field_data._id).update({
                    data:{
                        wait:this.data.field_data.wait + 1
                    }
                })
                wx.showToast({
                    title: '申请已提交',
                    icon: 'success',
                    duration: 2000
                })
                getApp().globalData.start = -1;
                getApp().globalData.stop = -1;
                wx.switchTab({
                    url: '/pages/index/index',
                })
            }
        })

    },
    // 将申请表相关数据汇总起来, 提交给数据库进行存储
    formSubmit_2(e) {


        if(this.data.result_this.message != '当前选择的时间区域可用')return;
        let value = e.detail.value;
        const db = wx.cloud.database();
        let apply_data = {
            // 申请人
            applicant: this.data.user_data.name,
            // 审批人
            director: this.data.director_data._id,
            // 抄送
            cc: e.detail.value.cc,  
            // 审批名称
            director_name: this.data.director_data.name,
            // 设备名称
            eq_name: this.data.eq_data.name,
            // 设备id
            eq_id: this.data.eq_data._id,
            filed_name: '',
            field_id: '',
            // 开始时间
            start_date: this.data.start_time_p,
            // 结束时间
            stop_date: this.data.end_time_p,
            // 申请单中的全部数据
            remarks: value,
            // 申请时间
            create_time: new Date().getTime(),
            project: e.detail.value.project,
            reason: e.detail.value.reason,
            tpm: e.detail.value.tpm,
            pipei: e.detail.value.pipei,
            // 默认状态 0,1,2
            state: 0
        }
        
            
            
        let new_data_used = getApp().globalData.new_date_used;
        if(new_data_used != -1 || new_data_used != undefined){
            db.collection('equipments').doc(this.data.id).update({
                data:{
                    date_used: new_data_used
                }
            })
            getApp().globalData.new_date_used = -1;
        }
        db.collection('applys').add({
            data: apply_data,
            success: res => {
                wx.showToast({
                    title: '申请已提交',
                    icon: 'success',
                    duration: 2000
                })
                wx.switchTab({
                    url: '/pages/index/index',
                })
            }
        })

    },
    formReset(e) {
    },
    switchToField() {
        if (this.data.type == 'eq') {
            wx.showToast({
                title: "当前正在申请设备，申请场地请退出重选",
                icon: 'none',
                duration: 2000
            })
        } else {
            this.setData({
                'showView': true,
                'btn_select': true
            })
        }
    },
    switchToEq() {
        if (this.data.type == 'field') {
            wx.showToast({
                title: "当前正在申请场地，申请设备请退出重选",
                icon: 'none',
                duration: 2000
            })
        } else {
            this.setData({
                'showView': false,
                'btn_select': false
            })
        }
    },
    dateselect() {
        getApp().globalData.date_used = this.data.date_used;
        wx.navigateTo({
            url: `/pages/dateselect/index`,
          });
    },

  //选择的入住与离店时间段
  selectDataMarkLine: function () {
    let dateList = this.data.dateList;
    let { checkInDate, checkOutDate } = wx.getStorageSync("ROOM_SOURCE_DATE");
    let curreInid = checkInDate.substr(0, 4) + "-" + (checkInDate.substr(5, 2) < 10 ? checkInDate.substr(6, 1) : checkInDate.substr(5, 2));//选择入住的id
    let curreOutid = checkOutDate.substr(0, 4) + "-" + (checkOutDate.substr(5, 2) < 10 ? checkOutDate.substr(6, 1) : checkOutDate.substr(5, 2));//选择离店的id
    let dayIn = checkInDate.substr(8, 2) >= 10 ? checkInDate.substr(8, 2) : checkInDate.substr(9, 1);//选择入住的天id
    let dayOut = checkOutDate.substr(8, 2) >= 10 ? checkOutDate.substr(8, 2) : checkOutDate.substr(9, 1);//选择离店的天id
    let monthIn = checkInDate.substr(5, 2) >= 10 ? checkInDate.substr(5, 2) : checkInDate.substr(6, 1);//选择入店的月id
    let monthOut = checkOutDate.substr(5, 2) >= 10 ? checkOutDate.substr(5, 2) : checkOutDate.substr(6, 1);//选择离店的月id
    if (curreInid == curreOutid) {//入住与离店是当月的情况
      for (let i = 0; i < dateList.length; i++) {
        if (dateList[i].id == curreInid) {
          let days = dateList[i].days;
          for (let k = 0; k < days.length; k++) {
            if (days[k].day >= dayIn && days[k].day <= dayOut) {
              days[k].class = days[k].class + ' bgitem';
            }
            if (days[k].day == dayIn) {
              days[k].class = days[k].class + ' active';
              days[k].inday = true;
            }
            if (days[k].day == dayOut) {
              days[k].class = days[k].class + ' active';
              days[k].outday = true;
            }
          }
        }
      }
    } else {//跨月
      for (let j = 0; j < dateList.length; j++) {
        if (dateList[j].month == monthIn) {//入住的开始月份
          let days = dateList[j].days;
          for (let k = 0; k < days.length; k++) {
            if (days[k].day >= dayIn) {
              days[k].class = days[k].class + ' bgitem';
            }
            if (days[k].day == dayIn) {
              days[k].class = days[k].class + ' active';
              days[k].inday = true;
            }
          }
        } else {//入住跨月月份
          if (dateList[j].month < monthOut && dateList[j].month > monthIn) {//离店中间的月份
            let days = dateList[j].days;
            for (let k = 0; k < days.length; k++) {
              days[k].class = days[k].class + ' bgitem';
            }
          } else if (dateList[j].month == monthOut) {//离店最后的月份
            let days = dateList[j].days;
            for (let k = 0; k < days.length; k++) {
              if (days[k].day <= dayOut) {
                days[k].class = days[k].class + ' bgitem';
              }
              if (days[k].day == dayOut) {
                days[k].class = days[k].class + ' active';
                days[k].outday = true;
              }
            }
          }
        }
      }
    }
    this.setData({
      dateList: dateList
    })
  },

  createDateListData: function () {
    let dateList = [];
    let now = new Date();
    let date_used = this.data.date_used;
    /*
      设置日期为 年-月-01,否则可能会出现跨月的问题
      比如：2017-01-31为now ,月份直接+1（now.setMonth(now.getMonth()+1)），则会直接跳到跳到2017-03-03月份.
        原因是由于2月份没有31号，顺推下去变成了了03-03
    */
    now = new Date(now.getFullYear(), now.getMonth(), 1);
    for (let i = 0; i < this.data.maxMonth; i++) {
      let momentDate = Moment(now).add(this.data.maxMonth - (this.data.maxMonth - i), 'month').date;
      let year = momentDate.getFullYear();
      let month = momentDate.getMonth() + 1;

      let days = [];
      let totalDay = this.getTotalDayByMonth(year, month);
      let week = this.getWeek(year, month, 1);
      //-week是为了使当月第一天的日期可以正确的显示到对应的周几位置上，比如星期三(week = 2)，
      //则当月的1号是从列的第三个位置开始渲染的，前面会占用-2，-1，0的位置,从1开正常渲染
      for (let j = -week + 1; j <= totalDay; j++) {
        let tempWeek = -1;
        if (j > 0)
          tempWeek = this.getWeek(year, month, j);
        let clazz = '';
        if (tempWeek == 0 || tempWeek == 6)
          clazz = 'week'
        if (j < DATE_DAY && year == DATE_YEAR && month == DATE_MONTH)
          //当天之前的日期不可用
          clazz = 'unavailable ' + clazz;
        else
          clazz = '' + clazz
        days.push({ day: j, class: clazz })
      }
      let dateItem = {
        id: year + '-' + month,
        year: year,
        month: month,
        days: days,
      }
      dateList.push(dateItem);
    }
    let sFtv = this.data.sFtv;
    for (let i = 0; i < dateList.length; i++){//加入公历节日
       for(let k = 0; k < sFtv.length; k++){
         if (dateList[i].month == sFtv[k].month){
            let days = dateList[i].days;
            for (let j = 0; j < days.length; j++){
                if (days[j].day == sFtv[k].day){
                    days[j].daytext = sFtv[k].name
                }
           }
         }
       }
    }

    
    // 重构data_used
    let new_data_used = {};
    for (let i = 0; i < dateList.length; i++){
        let days = dateList[i].days;
        for (let j = 0; j < days.length; j++){
            let month = dateList[i].month;
            let day = days[j].day;
            if(month < 10){
                month = "0" + month
            }
            if(day < 10){
                day = "0" + day
            }
            let date = dateList[i].year + '-' + month + "-" + day
            if(date_used[date]){
              days[j].status = date_used[date]
              if(date.split('-').length == 3){
                new_data_used[date] = date_used[date]
              }
            }else{
              days[j].status = 0
              if(date.split('-').length == 3){
                new_data_used[date] = 0
              }
            }
            
        }
    }
    getApp().globalData.new_date_used = new_data_used;
    this.setData({
      dateList: dateList
    });

    DATE_LIST = dateList;
  },

  /*
	 * 获取月的总天数
	 */
  getTotalDayByMonth: function (year, month) {
    month = parseInt(month, 10);
    let d = new Date(year, month, 0);
    return d.getDate();
  },
	/*
	 * 获取月的第一天是星期几
	 */
  getWeek: function (year, month, day) {
    let d = new Date(year, month - 1, day);
    return d.getDay();
  },
  /**
   * 点击日期事件
   */
  onPressDate: function (e) {
    let { year, month, day, status } = e.currentTarget.dataset;
    let date_used = this.data.date_used;
    let date = year + '-' + month + '-' + day
    let this_date_list = date_used[date]



    //点击后弹出窗口显示该日期下的具体使用人员
    wx.showModal({  
        title: '当前使用人员',  
        content: '项目+人员',  
        success: function(res) {  
            if (res.confirm) {  
            console.log('用户点击确定')  
            } else if (res.cancel) {  
            console.log('用户点击取消')  
            }  
        }  
    })  
    // let { year, month, day, status } = e.currentTarget.dataset;
    // //当前选择的日期为同一个月并小于今天，或者点击了空白处（即day<0），不执行
    // if ((day < DATE_DAY && month == DATE_MONTH) || day <= 0) return;
    // if (status>=10){return};

    // let tempMonth = month;
    // let tempDay = day;

    // if (month < 10) tempMonth = '0' + month
    // if (day < 10) tempDay = '0' + day

    // let date = year + '-' + tempMonth + '-' + tempDay;

    // //如果点击选择的日期A小于入住时间，则重新渲染入住时间为A
    // if ((this.data.markcheckInDate && Moment(date).before(this.data.checkInDate))) {
    //   this.setData({
    //     markcheckInDate: false,
    //     markcheckOutDate: false,
    //     dateList: DATE_LIST.concat()
    //   });
    // };

    // if (!this.data.markcheckInDate) {
    //   this.setData({
    //     checkInDate: date,
    //     markcheckInDate: true,
    //     dateList: DATE_LIST.concat()
    //   });
    // } else if (!this.data.markcheckOutDate) {
    //   this.setData({
    //     checkOutDate: date,
    //     markcheckOutDate: true,
    //   });
    //   this.selectDataMarkLine()
    //   console.log('入住:',this.data.checkInDate)
    //   console.log('离开',this.data.checkOutDate)
    //   //  入店，离店日期都必须在30天内
    //   let today = Date.parse(wx.getStorageSync('today'));
    //   let inDate=(Date.parse(this.data.checkInDate) - today)/(1*24*60*60*1000);
    //   let outDate=(Date.parse(this.data.checkOutDate) - today)/(1*24*60*60*1000);
    //   if(inDate > 30 || outDate> 30) {
    //     wx.showModal({ title: '提示', content: '抱歉，只接受30天之内的预定', showCancel: false })
    //     this.setData({ markcheckOutDate: false })
    //     return;
    //   }
    //   this.setData({
    //     start_date: this.data.checkInDate,
    //     stop_date: this.data.checkOutDate,
    //   })
    //   getApp().globalData.start = this.data.checkInDate;
    //   getApp().globalData.stop = this.data.checkOutDate;
    // }

    // this.renderPressStyle(year, month, day);
  },
  renderPressStyle: function (year, month, day) {
    // this.createDateListData();//重新点击时数据初始化
    let dateList = this.data.dateList;
    //渲染点击样式
    for (let i = 0; i < dateList.length; i++) {
      let dateItem = dateList[i];
      let id = dateItem.id;
      if (id === year + '-' + month) {
        let days = dateItem.days;
        for (let j = 0; j < days.length; j++) {
          let tempDay = days[j].day;
          if (tempDay == day) {
            days[j].class = days[j].class + ' active';
            days[j].inday = true;
            break;
          }
        }
        break;
      }
    }
    this.setData({
      dateList: dateList
    });
  },
  /**
   * 选择时间
   * @param {*} e 
   */
   changeDateTime(e) {
    let dateTimeArray = this.data.dateTimeArray,
      {
        type,
        param
      } = e.currentTarget.dataset;
    console.log(dateTimeArray)
    this.setData({
      [type]: e.detail.value,
      // [param]: dateTimeArray[0][e.detail.value[0]] + '-' + dateTimeArray[1][e.detail.value[1]] + '-' + dateTimeArray[2][e.detail.value[2]] + ' ' + dateTimeArray[3][e.detail.value[3]] + ':' + dateTimeArray[4][e.detail.value[4]] + ':' + dateTimeArray[5][e.detail.value[5]]
      [param]: dateTimeArray[0][e.detail.value[0]] + '-' + dateTimeArray[1][e.detail.value[1]] + '-' + dateTimeArray[2][e.detail.value[2]] + '-' + dateTimeArray[3][e.detail.value[3]]
    });

    console.log('开始时间为',this.data.start_time_p)
    console.log('结束时间为',this.data.end_time_p)
  },
  changeDateTimeColumn(e) {
    var dateArr = this.data.dateTimeArray,
      {
        type
      } = e.currentTarget.dataset,
      arr = this.data[type];
    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
    this.setData({
      dateTimeArray: dateArr,
      [type]: arr
    });
  },
  searchType(e) {
    let type = e.currentTarget.dataset.page[0];
    let id = e.currentTarget.dataset.page[1];
    let result = this.create_date_list()
    db.collection(type).doc(id).get().then(res =>{
      let _date_used = res.data.date_used;
      let result_this = {
        'message': '当前选择的时间区域可用',
        'data': {}
      }
      for(let i =0;i < result.length;i++){
        if( _date_used[result[i]] == undefined){
          
        }else if(_date_used[result[i]].length == 10){
          result_this.message = '您选择的时间区域内有不可选时间段';
          if(type == 'fields'){
            for(let j=0;j <_date_used[result[i]].length;j++){

              result_this.data.push(
                  [
                    result[i], 
                    _date_used[result[i]][j][0], 
                    _date_used[result[i]][j][1]
                  ]
                )
              if(result[i] in result_this.data){
                result_this.data[result[i]][1] = _date_used[result[i]][j][1]

              }else{
                result_this.data[result[i]][0] = _date_used[result[i]][j][0]
                result_this.data[result[i]][1] = _date_used[result[i]][j][1]  
              }
            }
          }else if(type == 'equipments'){
            result_this.data.push([result[i], _date_used[result[i]][0], _date_used[result[i]][1]])
          }
        }
      }
      this.setData({
        result_this: result_this
      })
      this.onShow()
    })
  },
  // 构建列表
  create_date_list(){

    let start_list = this.data.start_time_p.split('-');
    let end_list = this.data.end_time_p.split('-');
    let result = [];
    let run_mont = start_list[0]%4
    while((start_list[0] + '-' + start_list[1] + '-' + start_list[2] + '-' + start_list[3])!=(end_list[0] + '-' + end_list[1] + '-' + end_list[2] + '-' + end_list[3])){
      start_list[3] = (parseInt(start_list[3]) + 1) > 8?parseInt(start_list[3]) + 1 + '':'0' + (parseInt(start_list[3]) + 1);
      if(start_list[3] == '24'){
        start_list[3] = '00'
        start_list[2] = (parseInt(start_list[2]) + 1) > 9?parseInt(start_list[2]) + 1 + '':'0' + (parseInt(start_list[2]) + 1);
        switch(start_list[1]){
          case '01':
          case '03':
          case '05':
          case '07':
          case '08':
          case '10':
            if(start_list[2] == '32'){
              start_list[2] = '01'
              start_list[1] = (parseInt(start_list[1]) + 1) > 9?parseInt(start_list[1]) + 1 + '':'0' + (parseInt(start_list[1]) + 1);
            }
            break;
          case '12':
            if(start_list[2] == '32'){
              start_list[2] = '01';
              start_list[1] = '01';
              start_list[0] = (parseInt(start_list[1]) + 1) > 9?parseInt(start_list[1]) + 1 + '':'0' + (parseInt(start_list[1]) + 1);
            }
            break;
          case '04':
          case '06':
          case '09':
          case '11':
            if(start_list[2] == '31'){
              start_list[2] = '01'
              start_list[1] = (parseInt(start_list[1]) + 1) > 9?parseInt(start_list[1]) + 1 + '':'0' + (parseInt(start_list[1]) + 1);
            }
            break;
          case '02':
            if(run_mont==0 && start_list[2] == '30'){
              start_list[2] = '01'
              start_list[1] = (parseInt(start_list[1]) + 1) > 9?parseInt(start_list[1]) + 1 + '':'0' + (parseInt(start_list[1]) + 1);
            }else if(run_mont==0 && start_list[2] == '29'){
              start_list[2] = '01'
              start_list[1] = (parseInt(start_list[1]) + 1) > 9?parseInt(start_list[1]) + 1 + '':'0' + (parseInt(start_list[1]) + 1);
            }
            break;
        }
      }
      result.push(start_list[0] + '-' + start_list[1] + '-' + start_list[2] + '-' + start_list[3])

    }

    return result


  }
})